package cn.work.control;

import cn.work.service.goodsService;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ServiceDeleteServlet1", value = "/ServiceDeleteServlet1")
public class ServiceDeleteServlet1 extends HttpServlet {
    private goodsService gdao = new goodsService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        System.out.println("发送了吗");
        // 读取请求体中的 JSON 数据
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = request.getReader().readLine()) != null) {
            sb.append(line);
        }

        // 如果请求体为空，直接返回错误信息
        if (sb.length() == 0) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);  // 设置 400 错误
            PrintWriter out = response.getWriter();
            out.print("{\"success\": false, \"message\": \"请求数据为空\"}");
            out.flush();
            return;
        }

        // 使用 Gson 解析请求体中的 JSON 数据
        Gson gson = new Gson();
        RequestData requestData = gson.fromJson(sb.toString(), RequestData.class);

        // 如果解析失败或者 ID 无效，返回错误信息
        if (requestData == null || requestData.id <= 0) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);  // 设置 400 错误
            PrintWriter out = response.getWriter();
            out.print("{\"success\": false, \"message\": \"无效的服务ID\"}");
            out.flush();
            return;
        }

        int serviceId = requestData.id;
        System.out.println("Service ID: " + serviceId);  // 打印获取的 ID，用于调试

        // 调用 Service 层的删除方法
        boolean isDeleted = gdao.deleteService(serviceId);

        // 设置响应内容类型为 JSON
        PrintWriter out = response.getWriter();

        // 返回删除操作的结果
        if (isDeleted) {
            out.print("{\"success\": true}");
        } else {
            out.print("{\"success\": false, \"message\": \"删除失败\"}");
        }
        out.flush();
    }

    // 定义一个 RequestData 类，用于映射请求中的 JSON 数据
    static class RequestData {
        int id;
    }
}
